'''
Created on Feb 16, 2013

@author: jeh
'''

import numpy as np
from PyQt4 import QtCore, QtGui
from PIL import Image
import pyqtgraph as pg

from mImg import avg, hist_eq, Generate_Laplacian


 
class MainWindow(QtGui.QMainWindow):
    '''
    
    '''
    def __init__(self, parent=None, img=None):
        '''
        Constructor
        '''
        super(MainWindow, self).__init__()
        #QtGui.QMainWindow.__init__(self,parent)
        if img is not None:
            self.image = img
        self.__create_gui()
        self.__create_menu()
        self.__create_connections()
        self.original = img
        self.processed = None
        #self.load_plots_images()
   
    def __create_gui(self):
       
        # Create a central widget and main layout 
        cw = QtGui.QWidget()
        l = QtGui.QVBoxLayout()
        
        # Create some interaction objects
        hmenu = QtGui.QHBoxLayout() 
        self.cb = QtGui.QComboBox()
        self.cb.addItems(['Blur', 'HistEq', 'Laplace'])
        self.chkbox = QtGui.QCheckBox('Operate on Original?')
        self.btn_apply = QtGui.QPushButton('Apply')
        hmenu.addWidget(self.cb)
        hmenu.addWidget(self.chkbox)
        hmenu.addWidget(self.btn_apply)
        l.addLayout(hmenu)
        
        # Create the graphics view
        l_hplot = QtGui.QHBoxLayout()
        l_vimg = QtGui.QVBoxLayout()
        
        #self.plt1 = pg.PlotWidget()
        #self.plt2 = pg.PlotWidget()
        self.img1 = pg.ImageView()
        self.img2 = pg.ImageView()
        
        l_vimg.addWidget(self.img1)
        l_vimg.addWidget(self.img2)
        
        l.addLayout(l_hplot)
        l.addLayout(l_vimg)
        cw.setLayout(l)
        self.setCentralWidget(cw)
   
    def __create_connections(self):
        #  Connection signals for drop down change and apply        
        self.connect(self.btn_apply, QtCore.SIGNAL('clicked()'), self.on_apply)
    
    def __create_actions(self):
        pass
    
    
    def __create_menu(self):
        fileMenu = self.menuBar().addMenu("&File")
        exitAct = QtGui.QAction("E&xit", self, shortcut="Ctrl+Q",
                statusTip="Exit the application", triggered=self.on_exit)
        loadImg = QtGui.QAction("L&oad", self, shortcut="Ctrl+L",
                statusTip="Load an image file", triggered=self.on_load)
        fileMenu.addAction(loadImg)
        fileMenu.addSeparator()
        fileMenu.addAction(exitAct)

    def on_load(self):
        # File Types:
        ft_list = ["All Files (*)",
                   "JPEG Image (*.jpg)",
                   "JPEG Image (*.jpeg)",
                   "Tagged Image File Format (*.tif)",
                   "Tagged Image File Format (*.tiff)",
                   "Portable Network Graphics (*.png)"
                   ]
        qfd = QtGui.QFileDialog()
        mfile = qfd.getOpenFileName(self, "Image File to Open", "", ";;".join(ft_list))
        
        print str(mfile)
        img = Image.open(str(mfile))
        self.original = img.convert('L').rotate(-90).transpose(Image.FLIP_LEFT_RIGHT)
        arr_img1 = np.array(self.original)
        self.img1.setImage(arr_img1)
        
        
        
    def on_apply(self):
        if self.chkbox.isChecked():
            img = self.original
        else:
            img = self.processed
            
        if img is not None:
            selected = str(self.cb.currentText())
            if selected == "Blur":
                arr_img2 = np.array(avg(img))
            elif selected == "HistEq":
                arr_img2 = np.array(hist_eq(img))
            elif selected == "Laplace":
                arr_img2 = np.array(Generate_Laplacian(img))
            else:
                arr_img2 = np.array(img)
            self.img2.setImage(arr_img2)
            self.processed = Image.fromarray(arr_img2)
        else:
            pass
        
    
    def on_combo_select(self,ev):
        pass
  
  
    def on_exit(self):
        self.close()
   
    def closeEvent(self, event):
        reply = QtGui.QMessageBox.question(self, "Message",
                "Are you sure you want to quit",
                QtGui.QMessageBox.Yes,
                QtGui.QMessageBox.No)
        if reply == QtGui.QMessageBox.Yes:
            #self.cleanup_modules()
            event.accept()
            #logging.debug("MainWindow received close request, user accepted!")
        else:
            event.ignore()
        
if __name__ == "__main__":
    import sys
    import os
    os.chdir(os.path.split(os.getcwd())[0])
    app = QtGui.QApplication(sys.argv)
    someimg = Image.open('../img/winter_sm.jpg')
    mw = MainWindow(img=someimg)
    mw.setGeometry(100,100,800,600)
    mw.show()
    sys.exit(app.exec_())